#include <stdio.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <string.h>
#include <stdlib.h>
#include <pthread.h>


typedef struct linkdata
{
	int code;
	char name[32];
	char inputdata[128];
}userdata;

int sockfd=0;
int flag=0;
void *sendfunc(void *arg)
{
	userdata sendbuf;

	printf("plz input your name\n");
	scanf("%s",sendbuf.name);
	sendbuf.code=1;
	memset(sendbuf.inputdata,0,128);
	send(sockfd,&sendbuf,sizeof(sendbuf),0);
	printf("*************************\n");
	printf("<<*******my chat*******>>\n");
	printf("*************************\n");
	while(1)
	{
		scanf("%s",sendbuf.inputdata);
		if(strcmp(sendbuf.inputdata,"quit")==0)
		{
			sendbuf.code=3;
			send(sockfd,&sendbuf,sizeof(sendbuf),0);
			memset(sendbuf.inputdata,0,128);
			flag=1;
		}
		else
		{
			sendbuf.code=2;
			send(sockfd,&sendbuf,sizeof(sendbuf),0);
			memset(sendbuf.inputdata,0,128);
		}

	}

}

void *recvfunc(void *arg)
{
	while(1)
	{
		char recvbuf[256]={0};
		if(recv(sockfd,recvbuf,256,0)!=0)
		{
			printf("%s\n",recvbuf);
		}
	}
}

int main(int argc, const char *argv[])
{
	pthread_t mythread1;
	pthread_t mythread2;

	sockfd=socket(AF_INET,SOCK_STREAM,0);
	struct sockaddr_in serveraddr;
	serveraddr.sin_family=AF_INET;
	serveraddr.sin_addr.s_addr=inet_addr(argv[1]);
	serveraddr.sin_port=htons(atoi(argv[2]));

	socklen_t len=sizeof(serveraddr);
	connect(sockfd,(struct sockaddr *)&serveraddr,len);
	
	pthread_create(&mythread1,NULL,&sendfunc,NULL);
	pthread_create(&mythread2,NULL,&recvfunc,NULL);
	printf("pthread create success\n");
	pthread_detach(mythread1);
	pthread_detach(mythread2);
	while(flag!=1);

	return 0;
}
